/**
 * Project Name:emm-estate
 * File Name:ProjectTreeServiceFacadeImpl.java
 * Package Name:com.emm.yixun.estate.service.impl
 * Date:2017年10月31日下午3:06:50
 * Copyright (c) 2017, shihao.liu@qiaofang.info All Rights Reserved.
 *
 */

package com.emm.yixun.estate.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectNodeTreeService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.TreeDto;
import com.emm.yixun.common.model.TreeNode;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.estate.service.ProjectTreeServiceFacade;

/**
 * ClassName:ProjectTreeServiceFacadeImpl <br/>
 * Function: 项目房产树. <br/>
 * Date: 2017年10月31日 下午3:06:50 <br/>
 * 
 * @author Administrator
 * @version
 * @since JDK 1.6
 * @see
 */
@Service("projectTreeServiceFacade")
@WebService(name="com.emm.yixun.estate.service.ProjectTreeServiceFacade")
public class ProjectTreeServiceFacadeImpl implements ProjectTreeServiceFacade {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ProjectNodeTreeService projectNodeTreeService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private DataPermissionService dataPermissionService;

	@Override
	public ResponseList<TreeNode> treeNodeList(ProjectDto projectDto) {
		ResponseList<TreeNode> responseList = new ResponseList<TreeNode>();
		try {
			if (!StringUtils.isEmpty(projectDto.getCustomerId())) {
				// 从客户跳转过来，则取客户所在项目
				Customer customer = customerService.selectById(Long.valueOf(projectDto.getCustomerId()));
				projectDto.setId(customer.getProjectId());
			} else {
				// 数据权限
				if (SysConstants.openDataPermission) {
					String dataPermission = dataPermissionService.dataPermissionCondition(
									projectDto.getPermissionUserId(),
									projectDto.getResourcesCode(),
									projectDto.getPrefix(),
									projectDto.getColumnName());
					String[] dataPermissionArr = dataPermission.split(":");
					if ("00".equals(dataPermissionArr[0])) {
						responseList.setSuccess(true);
						return responseList;
					}
					projectDto.setDataPermission(dataPermissionArr[1]);
				}
			}
			List<TreeNode> treeNode = new ArrayList<TreeNode>();
			List<TreeDto> treeNodeList = projectNodeTreeService.queryProjectTreeNodeList(projectDto);
			treeNode=getChildrenTreeNode(treeNodeList);
			responseList.setEntity(treeNode);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统异常", e);
		}
		return responseList;
	}
	
	/**
	 * 
	 * getChildrenTreeNode:(组装树结构). <br/>
	 * @author Administrator
	 * @param treeDto
	 * @return
	 * @since JDK 1.6
	 */
	public List<TreeNode> getChildrenTreeNode(List<TreeDto> treeList){
		List<TreeNode> resultNode = new ArrayList<TreeNode>();
		for (TreeDto tree:treeList) {
			TreeNode treeNode = new TreeNode();
			treeNode.setId(tree.getId()); //最顶级项目
			treeNode.setText(tree.getText());
			List<TreeNode> treeNodeChildren = getChildren(tree);
			treeNode.setChildren(treeNodeChildren);
			resultNode.add(treeNode);
		}
		resultNode = getTreeNodeRel(resultNode);
		return resultNode;
	}
	public List<TreeNode> getTreeNodeRel(List<TreeNode> list){
		for (TreeNode node:list) {
			if(node.getChildren()==null||node.getChildren().size()<=0){
				node.setExpanded(false);
				node.setLeaf(true);
			}else{
				getTreeNodeRel(node.getChildren());
			}
		}
		return list;
	}
	public static List<TreeNode> getChildren(TreeDto treeDto){
		List<TreeNode> treeNode = new ArrayList<TreeNode>();
		Map<String, List<String>> groupChildrenMap = strToConverseMap(treeDto.getGroupChildren()); //组团
		Map<String, List<String>> buildingChildrenMap = strToConverseMap(treeDto.getBuildingChildren()); //楼栋
		Map<String, List<String>> unitChildrenMap = strToConverseMap(treeDto.getUnitChildren()); //单元 
		Map<String, List<String>> roomChildrenMap = strToConverseMap(treeDto.getRoomChildren()); //房间
		if(groupChildrenMap!=null){
			treeNode=getNodeChildrenInfo(treeDto.getId(), groupChildrenMap);
			for (int i = 0; i < treeNode.size(); i++) {
				TreeNode groupNode = treeNode.get(i);
					List<TreeNode> buildNodeList =  getNodeChildrenInfo(groupNode.getId(), buildingChildrenMap); //组团下的楼栋
					for (TreeNode buildNode:buildNodeList) {
							if(getNodeChildrenInfo(buildNode.getId(), unitChildrenMap).size()<=0){
								List<TreeNode> roomTreeNode =  getNodeChildrenInfo(buildNode.getId(), roomChildrenMap);
								buildNode.setChildren(roomTreeNode);
							}else{
								List<TreeNode> unitTreeNode = getNodeChildrenInfo(buildNode.getId(), unitChildrenMap);
								for (TreeNode unitNode:unitTreeNode) {
									List<TreeNode> roomTreeNode =  getNodeChildrenInfo(unitNode.getId(), roomChildrenMap);
									unitNode.setChildren(roomTreeNode);
								}
								buildNode.setChildren(unitTreeNode);
							}
						}
					groupNode.setChildren(buildNodeList); 
			}
		}
		return treeNode;
	}
	
	public static List<TreeNode> getNodeChildrenInfo(String key,Map<String, List<String>> map){
		List<TreeNode> treeNode = new ArrayList<TreeNode>();
		if(map!=null){
			for (Map.Entry<String, List<String>> mp:map.entrySet()) {
				if(mp.getKey().equals(key)){
					List<String> list = mp.getValue();
					for (int i = 0; i < list.size(); i++) {
						TreeNode node = new TreeNode();
						String[] childrenStr = list.get(i).split("\\?");
						node.setId(childrenStr[0]);
						if(childrenStr.length==2){
							node.setText(childrenStr[1]);
						}else{
							node.setText("未设置");
						}
						treeNode.add(node);
					}
				}
			}
		}
		return treeNode;
	}	
	public static Map<String, List<String>> strToConverseMap(String str){
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		if(!StringUtils.isEmpty(str)){
			String[] concatSpilt = str.split(",");
			for (int i = 0; i < concatSpilt.length; i++) {
				String[] strMaps = concatSpilt[i].split("/");
				if(strMaps == null || strMaps.length < 2) {
					continue;
				}
				String key = strMaps[0];
				String value = strMaps[1];
				if(map.containsKey(key)){ //包含
					map.get(key).add(value);			
				}else{ //不包含
					List<String> valueList = new ArrayList<String>();
					valueList.add(value);
					map.put(key, valueList);
				}
			}
		}
		return map;
	}
	public static void main(String[] args) {
		String[] str = "PREMISES_110?1期".split("\\?");
		System.err.println(str[0]);
		
	}
}
